package uk.ac.lkl.common.util.ds;



import java.util.Collection;


/**
 * Wraps up a list so that can see additions/removals.
 * 
 * @author Darren Pearce
 * @version $Revision: 596 $
 * @version $Date: 2008-02-14 15:16:39 +0000 (Thu, 14 Feb 2008) $
 * 
 */
public class NotifyingList<E> extends AbstractNotifyingList<E> {

    private static final long serialVersionUID = 1L;


    public NotifyingList(Class<E> elementClass) {
        super(elementClass);
    }


    public NotifyingList(Class<E> elementClass, E [] elements) {
        super(elementClass, elements);
    }


    public NotifyingList(Class<E> elementClass, Collection<E> collection) {
        super(elementClass, collection);
    }


    @Override
    public boolean add(E element) {
        int index = size();
        super.add(element);
        fireElementAdded(element, index);
        return true;
    }


    @Override
    public void add(int index, E element) {
        super.add(index, element);
        fireElementAdded(element, index);

        for (int i = index; i < size() - 1; i++) {
            E movedElement = get(i);
            fireElementMoved(movedElement, i, i + 1);
        }
    }


    public boolean removeElement(E element) {
        int index = indexOf(element);

        if (index == -1)
            return false;

        remove(index);
        return true;
    }


    public E remove(int index) {
        E result = super.remove(index);
        fireElementRemoved(result, index);

        for (int i = index; i < size(); i++) {
            E movedElement = get(i);
            fireElementMoved(movedElement, i + 1, i);
        }
        return result;
    }


    @Override
    public boolean remove(Object element) {
        // calls remove element
        return removeElement((E) element);
    }

}
